<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no,maximum-scale=1">
    <title>WebSocket</title>
    <style>
        * {
            margin: 0;
            padding: 0
        }
        .form-box {
            width: 400px;
            margin: auto;
            padding: 20px;
            box-sizing: border-box;
            text-align: center;
        }
        button,input {
            width: 100%;
            height: 30px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
<div class="form-box">
    <input id="addr" type="text" placeholder="websocekt 地址" value="ws://127.0.0.1:12345/echo">
    <button onclick="handleConnect()">连接客户端</button>
    <br>
    <input id="data-type" type="text" placeholder="数据类型" value="01">
    <br>
    <input id="data-value" type="text" placeholder="数据内容" value="Tom">
    <br>
    <button type="button" onclick="sendMsg()">发送</button>
</div>

<script>

    let socket;
    let reconnectInterval = 1000; // 初始重连时间间隔，单位毫秒
    let maxReconnectAttempts = 5000; // 最大重连次数
    let reconnectAttempts = 0; // 当前重连次数
    let connecting = false; // 标志是否正在尝试重连
    let loginStatus = false

    function handleConnect() {
        if(connecting) {
            console.log("正在连接中，请稍后");
            return 
        }
        connecting = true
        if (loginStatus) {
            socket.close();
            socket = null;
            console.log("连接已存在, 先断开连接");
        } else {
            connectWebSocket()
        }
    }

    function connectWebSocket() {
        connecting = true
        let ws_url = document.getElementById('addr').value;
        socket = new WebSocket(ws_url);

        socket.onopen = function (res) {
            loginStatus = true
            connecting = false; // 重置重连状态
            console.log("连接成功");
            reconnectAttempts = 0; // 重置重连计数

            socket.send(JSON.stringify({
              type: "01", data: "hello world"  
            })
            );
        }

        socket.onclose = function (e) {
            loginStatus = false
            connecting = false
            console.log("WebSocket closed");
            if (reconnectAttempts < maxReconnectAttempts) {
                attemptReconnect();
            }
        }

        socket.onerror = function (err) {
            console.log("WebSocket error")
        }

        socket.onmessage = function(e) {
            console.log("recv：" + e.data);
        };
    }

    function attemptReconnect() {
        if (connecting) return;
        connecting = true;
        console.log("正在重连...")
        setTimeout(() => {
            reconnectAttempts++;
            // reconnectInterval *= 2; // 使用指数退避算法，加倍重连时间间隔
            // console.log(`Attempting to reconnect (${reconnectAttempts}/${maxReconnectAttempts})...`);
            connectWebSocket();
        }, reconnectInterval);
    }

    function sendMsg() {
        
        let t = document.getElementById('data-type').value;
        let v = document.getElementById('data-value').value;
        console.log("发送消息",t,v);
        socket.send(
            JSON.stringify({
                type: t, data: v
            })
        );
    }
    // 启动 WebSocket 连接
    connectWebSocket();
</script>
</body>
</html>